package org.chen.ctrip.rmq.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.chen.ctrip.rmq.domain.AiProcessingMessage;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Component
public class AiDLQMessageListener implements MessageListenerConcurrently {
    
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(
            List<MessageExt> messages,
            ConsumeConcurrentlyContext context) {
        
        for (MessageExt message : messages) {
            try {
                String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
                AiProcessingMessage aiMessage = AiProcessingMessage.fromJson(messageBody);
                
                String reason = message.getUserProperty("reason");
                String originalTraceId = message.getUserProperty("originalTraceId");
                
                log.error("AI处理最终失败 - productId: {}, reason: {}, traceId: {}, originalTraceId: {}", 
                    aiMessage.getProductId(), reason, aiMessage.getTraceId(), originalTraceId);
                
                // 这里可以记录到数据库或发送告警
                saveFailureRecord(aiMessage, reason);
                
            } catch (Exception e) {
                log.error("处理死信消息异常: msgId={}", message.getMsgId(), e);
            }
        }
        
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
    
    private void saveFailureRecord(AiProcessingMessage message, String reason) {
        // 实现失败记录保存逻辑
        // 例如：保存到失败记录表，定期人工处理
        log.info("保存AI处理失败记录: productId={}, reason={}", message.getProductId(), reason);
    }
}